package spring.in.action.chapter_04;

import java.util.HashMap;
import java.util.Map;

import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TrackCounter
{
    Map<Integer, Integer> trackCounts = new HashMap<>();

    /**
     * 经过实际测试，参数名没有必要所有地方都一样， 只有注解中和注解的函数中的一样就可以了
     */
    @Pointcut("execution(* spring.in.action.chapter_04.BankDisc.playTrack(int)) && args(trackNumber)")
    public void trackPlayed(int trackNumber)
    {
    }

    @Before("trackPlayed(trackNumber)")
    public void countTrack(int trackNumber)
    {
        int currentCount = getPlayCount(trackNumber);
        trackCounts.put(trackNumber, currentCount + 1);
    }

    public int getPlayCount(int trackNumber)
    {
        Integer trackCount = trackCounts.get(trackNumber);
        return (trackCount == null) ? 0 : trackCount;
    }
}
